package com.cat2bug.junit.clazz;

import javassist.*;
import javassist.bytecode.*;

/**
 * 复制测试类字段
 */
public class CopyFiledOfTestClass extends AbstractTestClassDecorator {
    private CtField field;

    private Class<?> testCaseClass;

    public CopyFiledOfTestClass(ITestClassFactory factory,Class<?> testCaseClass, CtField field) {
        super(factory);
        this.field = field;
        this.testCaseClass = testCaseClass;
    }

    @Override
    public CtClass createTestClass(Class<?> clazz) throws Exception {
        CtClass ctClass = super.createTestClass(clazz);
        CtField copiedField = new CtField(field.getType(), field.getName(), ctClass);
        copiedField.setModifiers(field.getModifiers());
        // 获取字段上的注解属性
        AnnotationsAttribute annotationsAttribute = (AnnotationsAttribute) field.getFieldInfo().getAttribute(AnnotationsAttribute.visibleTag);
        // 如果字段上有注解属性，将其添加到复制得到的字段中
        if (annotationsAttribute != null) {
            copiedField.getFieldInfo().addAttribute(annotationsAttribute.copy(copiedField.getFieldInfo().getConstPool(), null));
        }

        ctClass.addField(copiedField);

        // TODO 没有拷贝值
        return ctClass;
    }

    private static String getDefaultInitValue(CtField field) {
        try {
            CtClass fieldType = field.getType();
            if (fieldType.equals(CtClass.booleanType)) {
                return "false";
            } else if (fieldType.equals(CtClass.byteType) || fieldType.equals(CtClass.shortType)
                    || fieldType.equals(CtClass.intType) || fieldType.equals(CtClass.longType)
                    || fieldType.equals(CtClass.floatType) || fieldType.equals(CtClass.doubleType)) {
                return "0";
            } else if (fieldType.equals(CtClass.charType)) {
                return "'\\u0000'";
            } else {
                return "null";
            }
        } catch (NotFoundException e) {
            e.printStackTrace();
            return "null";
        }
    }
}
